// 地图选择页面
const amapFile = require('../../utils/amap-wx.js'); // 高德地图微信小程序SDK
const myAmapFun = new amapFile.AMapWX({
    key: 'a6256fecde5ca1e3ce4ccd19de5e7a80' // 需要替换为您的高德地图Web API密钥
});

// 获取应用实例
const app = getApp();

Page({
    data: {
        longitude: 0, // 经度
        latitude: 0, // 纬度
        markers: [], // 地图标记点
        address: '', // 地址信息
        searchValue: '', // 搜索值
        suggestion: [], // 建议列表
        selectedAddress: null // 选中的地址信息
    },

    // 返回上一页
    goBack: function() {
        wx.navigateBack({
            delta: 1
        });
    },

    // 页面加载时
    onLoad: function(options) {
        // 获取当前位置
        this.getCurrentLocation();
    },

    // 页面显示时
    onShow: function() {
        // 获取当前位置
        this.getCurrentLocation();
    },

    // 获取当前定位
    getCurrentLocation: function() {
        let that = this;
        wx.showLoading({
            title: '定位中...',
        });

        wx.getLocation({
            type: 'gcj02',
            success: function(res) {
                console.log('当前位置信息:', res);
                that.setData({
                    longitude: res.longitude,
                    latitude: res.latitude,
                    markers: [{
                        id: 0,
                        longitude: res.longitude,
                        latitude: res.latitude,
                        width: 32,
                        height: 32,
                        iconPath: '../../static/images/marker.png',
                        callout: {
                            content: '当前位置',
                            padding: 10,
                            borderRadius: 5
                        }
                    }]
                });

                // 逆地址解析，把经纬度转换为地址信息
                that.getAddressByLocation(res.longitude, res.latitude);
            },
            fail: function(err) {
                console.error('获取位置失败:', err);
                wx.showToast({
                    title: '获取位置失败',
                    icon: 'none'
                });
            },
            complete: function() {
                wx.hideLoading();
            }
        });
    },

    // 通过经纬度获取地址信息
    getAddressByLocation: function(longitude, latitude) {
        let that = this;
        myAmapFun.getRegeo({
            location: longitude + ',' + latitude,
            success: function(data) {
                console.log('地址信息:', data);
                if (data && data.length > 0) {
                    let addressInfo = data[0];
                    let address = addressInfo.regeocodeData.formatted_address;
                    let addressComponent = addressInfo.regeocodeData.addressComponent;

                    // 更新地址信息
                    that.setData({
                        address: address,
                        selectedAddress: {
                            name: addressInfo.name || address,
                            address: address,
                            province: addressComponent.province,
                            city: addressComponent.city,
                            district: addressComponent.district,
                            longitude: longitude,
                            latitude: latitude
                        }
                    });
                }
            },
            fail: function(info) {
                console.error('获取地址信息失败:', info);
                wx.showToast({
                    title: '获取地址信息失败',
                    icon: 'none'
                });
            }
        });
    },

    // 搜索地点
    searchPOI: function(e) {
        let that = this;
        let keywords = e.detail.value;

        that.setData({
            searchValue: keywords
        });

        if (keywords.trim() === '') {
            that.setData({
                suggestion: []
            });
            return;
        }

        myAmapFun.getInputtips({
            keywords: keywords,
            location: that.data.longitude + ',' + that.data.latitude,
            success: function(data) {
                console.log('搜索结果:', data);
                if (data && data.tips) {
                    that.setData({
                        suggestion: data.tips
                    });
                }
            },
            fail: function(info) {
                console.error('搜索地点失败:', info);
            }
        });
    },

    // 选择搜索结果
    selectAddress: function(e) {
        let index = e.currentTarget.dataset.index;
        let item = this.data.suggestion[index];
        console.log('选择的位置:', item);

        if (item && item.location) {
            let locationArray = item.location.split(',');
            let longitude = parseFloat(locationArray[0]);
            let latitude = parseFloat(locationArray[1]);

            this.setData({
                longitude: longitude,
                latitude: latitude,
                markers: [{
                    id: 0,
                    longitude: longitude,
                    latitude: latitude,
                    width: 32,
                    height: 32,
                    iconPath: '../../static/images/marker.png',
                    callout: {
                        content: item.name,
                        padding: 10,
                        borderRadius: 5
                    }
                }],
                searchValue: '',
                suggestion: []
            });

            // 获取选择位置的详细地址信息
            this.getAddressByLocation(longitude, latitude);
        } else {
            // 如果没有location信息，使用关键字进行搜索
            let that = this;
            myAmapFun.getPoiAround({
                keywords: item.name,
                success: function(data) {
                    console.log('周边搜索结果:', data);
                    if (data && data.markers && data.markers.length > 0) {
                        let poi = data.markers[0];
                        let longitude = parseFloat(poi.longitude);
                        let latitude = parseFloat(poi.latitude);

                        that.setData({
                            longitude: longitude,
                            latitude: latitude,
                            markers: [{
                                id: 0,
                                longitude: longitude,
                                latitude: latitude,
                                width: 32,
                                height: 32,
                                iconPath: '../../static/images/marker.png',
                                callout: {
                                    content: poi.name,
                                    padding: 10,
                                    borderRadius: 5
                                }
                            }],
                            searchValue: '',
                            suggestion: []
                        });

                        // 获取选择位置的详细地址信息
                        that.getAddressByLocation(longitude, latitude);
                    }
                },
                fail: function(info) {
                    console.error('周边搜索失败:', info);
                }
            });
        }
    },

    // 地图移动结束事件
    regionchange: function(e) {
        // 当地图移动结束时，获取中心点位置
        if (e.type === 'end' && e.causedBy === 'drag') {
            let that = this;
            this.mapCtx = wx.createMapContext('myMap');
            this.mapCtx.getCenterLocation({
                success: function(res) {
                    that.getAddressByLocation(res.longitude, res.latitude);
                    that.setData({
                        longitude: res.longitude,
                        latitude: res.latitude,
                        markers: [{
                            id: 0,
                            longitude: res.longitude,
                            latitude: res.latitude,
                            width: 32,
                            height: 32,
                            iconPath: '../../static/images/marker.png'
                        }]
                    });
                }
            });
        }
    },

    // 确认选择位置
    confirmLocation: function() {
        let selectedAddress = this.data.selectedAddress;
        if (!selectedAddress) {
            wx.showToast({
                title: '请先选择位置',
                icon: 'none'
            });
            return;
        }

        // 将选择的地址信息返回给前一个页面
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - 2]; // 前一个页面

        // 直接设置上一个页面的数据
        prevPage.setData({
            'address.name': selectedAddress.name,
            'address.full': selectedAddress.address,
            'address.latitude': selectedAddress.latitude,
            'address.longitude': selectedAddress.longitude,
            'address.province': selectedAddress.province,
            'address.city': selectedAddress.city,
            'address.county': selectedAddress.district
        });

        // 返回前一个页面
        wx.navigateBack();
    },

    // 清空搜索
    clearSearch: function() {
        this.setData({
            searchValue: '',
            suggestion: []
        });
    }
});